# Create your views here.

from users.models import UserProperty, OptionsProperty, UserPropertyValue

from django import forms
from django.core.urlresolvers import reverse
from django.contrib.auth import logout
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.db import transaction
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Template, context, RequestContext
from django.utils.translation import ugettext_lazy as _

def create_form(properties, data=None):
    if data:
        f = UserCreationForm(data)
    else:
        f = UserCreationForm()

    # le agrego un campo para que el first_name y last_name
    f.fields['first_name'] = forms.CharField(label=_('First (Given) Name'), \
                                        max_length=30)
    f.fields['last_name'] = forms.CharField(label=_('Last (Family) Name'), \
                                        max_length=30)
    f.fields['email'] = forms.EmailField(label=_('Email'), max_length=75)
                                            
    
    for property in properties:
        f.fields[property.key] = property.get_form_field()
    return f
        
@transaction.commit_on_success
def create_user(request):
    properties = UserProperty.objects.all()
    form = create_form(properties, request.POST)
    if form.is_valid():
        user =  User.objects.create_user(form.cleaned_data['username'],
                                    form.cleaned_data['email'],
                                    form.cleaned_data['password1'])
        user.first_name = form.cleaned_data['first_name']
        user.last_name = form.cleaned_data['last_name']
        user.save()

        for property in properties: 
            value = form.cleaned_data[property.key]
            if isinstance(value, list):
                value = u';'.join(value)
            user_property_value = UserPropertyValue(property=property, \
                                                user=user, \
                                                value=value)
            user_property_value.save()
        return HttpResponseRedirect(reverse('static.views.index'))
    return render_to_response('users/create.html', dict(form=form), \
                context_instance=RequestContext(request))
